<template>
  <div class="reset-password">
    <el-card class="box-card">
      <h1>重置密码</h1>
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input v-model="form.oldPassword" type="password" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" type="password" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" class="reset"
            >重置密码</el-button
          >
          >
        </el-form-item>
        <!-- <el-form-item>
            <el-button type="forget"  @click="forgercode">忘记密码</el-button>
          </el-form-item> -->
        </el-form>
        <div class="info">
          <h1>密码忘了</h1>
          <p1 class="find">通过以下方式找回：</p1>
          <el-button @click="selectedMethod = 'email'" class="findemail">通过电子邮箱找回</el-button>
          <el-button @click="selectedMethod = 'phone'" class="findtelephone">通过电话号码找回</el-button>
          <!-- <el-button @click="selectedMethod = 'id'">通过身份证号找回</el-button> -->
        </div>
        <div v-if="selectedMethod" class="reset-options">
          <el-form v-if="selectedMethod === 'email'" :model="form" :rules="emailRules" ref="emailForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="邮箱" prop="email" >
              <el-input v-model="form.email" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sendResetEmail" class="sendemail">发送邮件</el-button>
            </el-form-item>
            <p v-if="emailSuccess" class="success">{{ emailSuccess }}</p>
            <p v-if="emailErrorMessage" class="error">{{ emailErrorMessage }}</p>
          </el-form>
          <el-form v-if="selectedMethod === 'phone'" :model="form" :rules="phoneRules" ref="phoneForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sendResetSMS" class="sendmsg">发送短信</el-button>
            </el-form-item>
            <p v-if="phoneSuccess" class="success">{{ phoneSuccess }}</p>
            <p v-if="phoneErrorMessage" class="error">{{ phoneErrorMessage }}</p>
          </el-form>
          <el-form v-if="selectedMethod === 'id'" :model="form" :rules="idRules" ref="idForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="身份证号" prop="idNumber">
              <el-input v-model="form.idNumber" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sendResetId">发送重置通知</el-button>
            </el-form-item>
            <p v-if="idSuccess" class="success">{{ idSuccess }}</p>
            <p v-if="idErrorMessage" class="error">{{ idErrorMessage }}</p>
          </el-form>
        </div>
      </el-card>
    </div>
  </template>
  
  <script>
  import { reactive, ref } from 'vue';
  import axios from 'axios';
  
  export default {
    setup() {
    const form = reactive({
        oldPassword: '',
        newPassword: '',
        email: '',
        phone: '',
        idNumber: ''
      });
  
      const rules = {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ]
      };
  
      const emailRules = {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
        ]
      };
  
      const phoneRules = {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^[0-9]{11}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ]
      };
  
      const idRules = {
        idNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /^[0-9]{18}$/, message: '请输入有效的身份证号', trigger: 'blur' }
        ]
      };
  

    const emailSuccess = ref('')
    const emailErrorMessage = ref('')
      const phoneSuccess = ref('');
      const phoneErrorMessage = ref('');
      const idSuccess = ref('');
      const idErrorMessage = ref('');
    const selectedMethod = ref('')
      const isSubmitting = ref(false);
  
      const validateOldPassword = () => {
        if (!form.oldPassword) {
          form.oldPasswordError = '旧密码不能为空';
        } else {
          form.oldPasswordError = '';
        }
      };
  
      const validateNewPassword = () => {
        if (!form.newPassword) {
          form.newPasswordError = '新密码不能为空';
        } else {
          form.newPasswordError = '';
        }
      };
  
      const handleSubmit = async () => {
      const formRef = ref('form')
      formRef.value.validate(async (valid) => {
          if (valid) {
          isSubmitting.value = true
            try {
              await axios.post('/api/reset-password', {
                oldPassword: form.oldPassword,
                newPassword: form.newPassword
              });
            alert('密码已成功重置')
            } catch (error) {
            alert('重置密码失败，请稍后重试')
            } finally {
            isSubmitting.value = false
            }
          }
        });
      };
  
      const sendResetEmail = async () => {
        const emailFormRef = ref('emailForm');
        emailFormRef.value.validate(async valid => {
          if (valid) {
            isSubmitting.value = true;
            emailSuccess.value = '';
            emailErrorMessage.value = '';
            try {
              await axios.post('/api/send-reset-email', { email: form.email });
              emailSuccess.value = '重置邮件已发送，请检查您的邮箱';
            } catch (error) {
              emailErrorMessage.value = '发送重置邮件失败，请稍后重试';
            } finally {
              isSubmitting.value = false;
            }
          }
      })
      };
  
      const sendResetSMS = async () => {
        const phoneFormRef = ref('phoneForm');
        phoneFormRef.value.validate(async valid => {
          if (valid) {
            isSubmitting.value = true;
            phoneSuccess.value = '';
            phoneErrorMessage.value = '';
            try {
              await axios.post('/api/send-reset-sms', { phone: form.phone });
              phoneSuccess.value = '重置短信已发送，请检查您的手机';
            } catch (error) {
              phoneErrorMessage.value = '发送重置短信失败，请稍后重试';
            } finally {
              isSubmitting.value = false;
            }
          }
        });
      };
  
      const sendResetId = async () => {
        const idFormRef = ref('idForm');
        idFormRef.value.validate(async valid => {
          if (valid) {
            isSubmitting.value = true;
            idSuccess.value = '';
            idErrorMessage.value = '';
            try {
              await axios.post('/api/send-reset-id', { idNumber: form.idNumber });
              idSuccess.value = '重置通知已发送，请检查';
            } catch (error) {
              idErrorMessage.value = '发送重置通知失败，请稍后重试';
            } finally {
              isSubmitting.value = false;
            }
          }
        });
      };
  
      return {
        form,
        rules,
        emailRules,
        phoneRules,
        idRules,
        emailSuccess,
        emailErrorMessage,
        phoneSuccess,
        phoneErrorMessage,
        idSuccess,
        idErrorMessage,
        selectedMethod,
        isSubmitting,
        validateOldPassword,
        validateNewPassword,
        handleSubmit,
        sendResetEmail,
        sendResetSMS,
        sendResetId
      };
    }
  };
  </script>
  
  <style scoped>
  .reset-password {

    height:400px;
    width: 900px;
    margin-top: 70px;
    text-align: center;
    position:relative;
    left:170px;

  }
  .reset{
    position: relative;
    left:89px;
    max-width: 200px;
  }
  
  .demo-ruleForm {
    max-width: 420px;
    margin: 0 auto;
    position: relative;
    left: -43px;
    

  }
  
  .reset-options {
    margin-top: 20px;
  }
  
  .info {
    margin-top: 20px;
  }
  
  .error {
    color: red;
  }
  
  .success {
    color: green;
  }
  .sendemail{
    position: relative;
    left:89px;
  }
  .sendmsg{
    position: relative;
    left:89px;
  }
  .find{
    position: relative;
    left:-63px;
  }
  .findemail{
    position: relative;
    left: -50px;
  }
  .findtelephone{
    position: relative;
    left: -50px;
  }
  </style>
  